<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NImage,
  NForm,
  NFormItem,
  NSelect,
  NDatePicker,
  NEllipsis
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h, watch ,onDeactivated} from 'vue'
import { sendRequest } from '@/utils/api'
import type { collectNoticeModel } from '@/api/collectNotice'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import VBackImg from '@/assets/images/back.png'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import TableView from '@/components/TableViewItemManage.vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()
const route = useRoute()
const listOption = ref([])
const listStatusOption = ref([])
const tags = useTagStore().tags
const tableData = ref<collectNoticeModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
// const datetime = computed<[string, string]>({
//   get() {
//     return [form.startDate, form.endDate]
//   },
//   set(v) {
//     form.startDate = v[0]
//     form.endDate = v[1]
//   }
// })
const datetime = ref(null)
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const [form, resetForm] = useQueryForm(
  reactive({
    startDate: null,
    endDate: null,
    name: null,
    statusCode: null,
    collectMethodCode: null
  }),
  () => {
    datetime.value = null
    form.startDate = null
    form.endDate = null
    form.name = null
    form.statusCode = null
    form.collectMethodCode = null
  }
)
const changeDate = (v: any) => {
  datetime.value = v
  form.startDate = v ? v[0] : null
  form.endDate = v ? v[1] : null
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  
    tags.splice(index, 1)
if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
const columns: DataTableColumns<collectNoticeModel> = [
  {
    title: '序号',
    key: 'orderIndex',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    },
    width: '5rem',
    align: 'center'
  },
  {
    title: '姓名',
    key: 'userName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '联系方式',
    key: 'phone',
    width: '10rem',
    align: 'center'
  },
  {
    title: '提交时间',
    key: 'commitTime',
    width: '10rem',
    align: 'center'
  },
  {
    title: '征集方式',
    key: 'collectMethodName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '审核状态',
    key: 'statusName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '备注',
    key: 'feedbackNotes',
    width: '15rem',
    align: 'center',
    render:(e:any)=>{
      return h(
        NEllipsis,
        {
          style:{
            minWidth: '15rem'
          },
          tooltip: {
            contentStyle: {
              maxWidth: '400rem'
            }
          }
        },
        {
          default:()=>e.feedbackNotes
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'info',
          quaternary: true,
          style: {
            display: e.statusName === '待处理' ? 'inline-block' : 'none'
          },
          onClick: () => handleP(e)
        },
        {
          default: () => '审核'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      )
    ]
  }
]
const tableLoading = ref(false)
const noticeId = ref()
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  noticeId.value = router.currentRoute.value.params.noticeId
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<collectNoticeModel>>({
    module: 'collectNotice',
    api: 'listProvide',
    override: {
      params: {
        noticeId: noticeId.value,
        name: form.name,
        statusCode: form.statusCode,
        collectMethodCode: form.collectMethodCode,
        startDate: form.startDate,
        endDate: form.endDate,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A30'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
//状态下拉
const getSFunction = async () => {
  listStatusOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A38'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listStatusOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const handleP = (e: any) => {
  router.push({ name: 'informationSolicitationEdit', params: { id: e.id } })
}
const handleDetail = (e: any) => {
  router.push({ name: 'informationSolicitationDetail', params: { id: e.id } })
}
onMounted(() => {
  noticeId.value = router.currentRoute.value.params.noticeId
  getFunction()
  getSFunction()
  queryTableData(true)
})
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  () => {
    if (route.name == 'informationSolicitation') {
      form.name=null
      form.startDate=null
      form.endDate=null
      form.statusCode=null
      form.collectMethodCode=null
      datetime.value = null
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <NFormItem label="姓名:">
            <NInput
              placeholder="输入姓名"
              v-model:value="form.name"
              style="width: 150px"
            />
          </NFormItem>
          <NFormItem label="审核状态:">
            <NSelect
              :options="listStatusOption"
              v-model:value="form.statusCode"
              placeholder="请选择审核状态"
              clearable
              style="width: 150px"
            />
          </NFormItem>
          <NFormItem label="征集方式:">
            <NSelect
              :options="listOption"
              v-model:value="form.collectMethodCode"
              placeholder="请选择征集方式"
              clearable
              style="width: 150px"
            />
          </NFormItem>
          <NFormItem label="日期范围:">
           <NDatePicker input-readonly
              v-model:formatted-value="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"  default-time="00:00:00"
              @update:formatted-value="changeDate"
              clearable
            />
          </NFormItem>
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px;margin-right: 10px;"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
            <NButton
              type="primary"
              ghost
              style="width: 78px"
              @click="resetForm"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
      </NSpace>
    </template>
    <template #table="props">
      <NDataTable
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
      />
    </template>
    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <FixedAction>
    <NSpace>
      <NButton
        style="width: 78px; color: #5fb17f"
        ghost
        @click="goBack"
      >
        <template #icon>
          <NImage
            :src="VBackImg"
            style="width: 50rem; height: 50rem"
            preview-disabled
          ></NImage>
        </template>
        返回
      </NButton>
    </NSpace>
  </FixedAction>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
